package com.elink.enginerring.label.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.label.dao.LabelMapper;
import com.elink.enginerring.label.entity.Label;
import com.elink.enginerring.util.JSONUtil;

@Service
public class LabelService implements ILabelService {
	@Autowired
	private LabelMapper tagMapper;

	@Override
	public Map<String, Object> getList() {
		return JSONUtil.getJSON(ErrorType.SUCCESS, tagMapper.getList());
	}

	@Override
	public Map<String, Object> add(Label label) {
		label.setSequence(tagMapper.getMaxSeq());
		return JSONUtil.getJSON(ErrorType.SUCCESS,tagMapper.insertSelective(label));
	}

	@Override
	public Map<String, Object> modify(Label label) {
		return JSONUtil.getJSON(ErrorType.SUCCESS,tagMapper.updateByPrimaryKeySelective(label));
	}

	@Override
	public Map<String, Object> del(String ids) {
		tagMapper.del(ids);
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> order(String id_seq) {
		for (String str : id_seq.split(",")) {
			tagMapper.order(str.split("_")[0], str.split("_")[1]);
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Object addBatch(String tags, String userId) {
		
		int maxId = tagMapper.getMaxId();
		int maxSeq = tagMapper.getMaxSeq();
		String tagId = "";
		List<Label> list = new ArrayList<Label>();
		for (String label : tags.split(",")) {
			Label l = new Label();
			l.setLabelId(++maxId);
			l.setUserId(userId);
			l.setLabelName(label);
			l.setSequence(++maxSeq);
            tagId += maxId +",";
            list.add(l);
		}
		 tagMapper.insertBatch(list);
		 return tagId.substring(0,tagId.length()-1);
	}
	@Override
	public Object updateBatch(String tags, String oldTagId, String userId) {
		//1,根据主键删除旧的tag
		tagMapper.del(oldTagId);
		
		//2,插入新的tag
		int maxId = tagMapper.getMaxId();
		int maxSeq = tagMapper.getMaxSeq();
		String tagId = "";
		List<Label> list = new ArrayList<Label>();
		for (String label : tags.split(",")) {
			Label tag = new Label();
            tag.setLabelId(++maxId);
            tag.setUserId(userId);
            tag.setLabelName(label);
            tag.setSequence(++maxSeq);
            list.add(tag);
            tagId += maxId +",";
		}
		 tagMapper.insertBatch(list);
		 return tagId.substring(0,tagId.length()-1);
	}	
}
